class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def sumNumbers(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        total_num = [0]

        def search(root, s):
            s += str(root.val)
            if not (root.left or root.right):
                total_num[0] += int(s)
            else:
                if root.left:
                    search(root.left, s)
                if root.right:
                    search(root.right, s)

        search(root, '')

        return total_num[0]